<template>
<!--查询-->
<div style="margin-bottom: 15px;">
  角色名:<el-input v-model="form.menuName" placeholder="请输入菜单名" style="width: 240px;"></el-input>
  <el-button type="primary" @click="getMenuList">查询</el-button>
</div>
  <!--菜单列表-->
  <el-table :data="menuData" border style="width: 100%">
    <el-table-column prop="menuId" label="编号" align="center" />
    <el-table-column prop="menuName" label="菜单名称" align="center" />
    <el-table-column prop="url" label="菜单Url" align="center" />
    <el-table-column prop="menuNames.menuName" label="父级菜单名称" align="center" />
    <el-table-column prop="createdBy" label="创建人" align="center" />
    <el-table-column prop="createdDate" label="创建日期" align="center" />
    <el-table-column prop="updatedBy" label="修改人" align="center" />
    <el-table-column prop="updatedDate" label="修改日期" align="center" />
    <el-table-column label="操作" align="center" width="170px" >
      <template v-slot="scope">
        <el-button type="primary" @click="UpdateMenu(scope.row.menuId)" >修改</el-button> &nbsp;
        <el-button type="danger" @click="searchMenuCount(scope.row.menuId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

<!--分页-->
<table>
  <thead></thead>
  <tbody>
    <tr>
      <td>
        <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[3, 5, 7, 9]" :background="true" layout="total,slot, sizes" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <span>
            ，每页{{ form.pageSize }}条，当前第:{{ form.pageIndex }}/{{ form.pageCount }}页
          </span>
        </el-pagination>
      </td>

      <td>
        <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[100, 200, 300, 400]" :background="true" layout="slot, prev, pager, next" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <el-button type="primary" class="btn-prev" @click="handleCurrentChange(1)" :disabled="form.pageIndex==1">首页</el-button>
        </el-pagination>
      </td>

      <td>
        <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[100, 200, 300, 400]" :background="true" layout="slot, jumper" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <el-button type="primary" class="btn-prev" @click="handleCurrentChange(form.pageCount)" :disabled="form.pageIndex==form.pageCount">尾页</el-button>
        </el-pagination>
      </td>
    </tr>
  </tbody>
</table>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

import {useRoute,useRouter} from 'vue-router'

const route = useRoute();
const router = useRouter();

const form: any = reactive({
  pageIndex: 1,
  pageSize: 5,
  menuName: '',
  pageCount:0,
  totalCount:0,
})

onMounted(() => {
  getMenuList()
})

//分页
const handleSizeChange = (val: number) => {
  form.pageSize = val;
  getMenuList()
}
const handleCurrentChange = (val: number) => {
  form.pageIndex = val;
  getMenuList()
}

//获取Token字符串中的UserId
var token:any = localStorage.getItem("Tokens")
console.log(token);
//分割JWT字符串
const [header, payload, signature] = token.split(".");
//Base64解码Payload
const payloadDecoded = atob(payload);
//解析JSON字符串
const payloadParsed=JSON.parse(payloadDecoded)
//提取userId和roleId
form.userId = payloadParsed.sub;
const roleId = payloadParsed['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'];  
console.log(form.userId);
console.log(roleId);


const menuData:any=ref([])
//获取菜单列表
const getMenuList = () => {
  let menu = {
    //userId:sessionStorage.getItem("userId")
    userId: form.userId,
    pageIndex: form.pageIndex,
    pageSize: form.pageSize,
    menuName:form.menuName
  }
  axios.post('/api/MenuManagement/SearchMenuList',menu).then(res=>{
    console.log(res);
    menuData.value = res.data.data.list;
    form.pageCount = res.data.data.pageCount;
    form.totalCount = res.data.data.totalCount;
  }).catch(err=>{
    console.log(err);
    
  })    
}

//修改
const UpdateMenu = (menuId:number) => {
  router.push({
    'name': 'UpdateMenu',
    query: {
      menuId:menuId
    }
  })
}

//删除
const searchMenuCount = (menuId: number) => {
  let delMenu = {
    menuId: menuId
  }
  axios.post('/api/MenuManagement/SearchMenuCount', delMenu).then(res => {
    console.log(res);
    if (res.data.code >0) {
      DelMenuChildren(menuId)
    } else {
      DelMenu(menuId)
    }
  }).catch(err => {
    console.log(err);
    
  })    
}

//删除
const DelMenu = (menuId: number) => {
  let delMenu = {
    menuId:menuId
  }
  ElMessageBox.confirm(
      '确定要删除吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      }
    )
      .then(() => {
        axios.post('/api/MenuManagement/DeleteMenu', delMenu).then(res => {
          console.log(res);
          if (res.data.code >0) {
            ElMessage.success("删除成功!")
            //刷新页面
            getMenuList()
          } else {
            ElMessage.error("删除失败!");
            return
          }
        }).catch(err => {
          console.log(err);

        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
      })
}

//删除当前菜单及所有子集及所有子集的子集
const DelMenuChildren = (menuId: number) => {
  let delChildrenMenu = {
    menuId: menuId
  }
  ElMessageBox.confirm(
    '删除当前菜单及所有子集及所有子集的子集?',
    '警告',
    {
      confirmButtonText: '确定', 
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
      axios.post('/api/MenuManagement/DeleteMenu', delChildrenMenu).then(res => {
        console.log(res);
        if (res.data.code >0) {
          ElMessage.success("删除成功!")
          //刷新页面
          getMenuList()
        } else {
          ElMessage.error("删除失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

</script>

<style scoped>

</style>